package com.wutuo.aggragation.roster.controller;

import cn.apestar.ChatInstance;
import cn.apestar.agg.common.security.BaseAuthController;
import cn.apestar.cloud.api.enums.MessageType;
import cn.apestar.cloud.api.enums.MessageWTType;
import cn.apestar.cloud.api.enums.PeoPleType;
import cn.apestar.core.base.BaseMessage;
import cn.apestar.core.framework.exception.BusinessException;
import cn.apestar.core.http.AppType;
import cn.apestar.user.api.UserAPIService;
import cn.apestar.user.api.enums.RoleTypeEnum;
import cn.apestar.user.provider.info.domain.User;
import cn.apestar.user.provider.institution.enums.AuditStateEnum;
import cn.apestar.user.provider.institution.request.UserAndInstituionRequest;
import cn.apestar.user.provider.institution.response.InstitutionResponse;
import cn.apestar.user.provider.institution.response.UserAndInstituionResponse;
import cn.apestar.user.provider.institution.service.UserAndInstitutionService;
import com.wutuo.common.UserAndInstitutionWTService;
import com.wutuo.institution.api.InstitutionWTAPIService;
import com.wutuo.roster.api.ChildApplyAPIService;
import com.wutuo.roster.api.RosterAPIService;
import com.wutuo.roster.api.request.AuditChildApplyRequest;
import com.wutuo.roster.api.request.ChildApplyRequest;
import com.wutuo.roster.api.request.ListChildApplyRequest;
import com.wutuo.roster.api.response.ChildApplyResponse;
import com.wutuo.roster.provider.component.ChildApplyDataConvert;
import com.wutuo.roster.provider.domain.ChildApply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * 孩子申请 <br>
 * 详细说明.
 * <p>
 *
 * @author lvh
 * @version 1.0
 */
@RestController
@RequestMapping(value = "/childApply", produces = "application/json")
public class ChildApplyController extends BaseAuthController {

    @Autowired
    private ChildApplyAPIService childApplyService;

    @Autowired
    private RosterAPIService rosterService;

    @Autowired
    private UserAPIService userService;

    @Autowired
    private UserAndInstitutionService userAndInstitutionService;

    @Autowired
    private UserAndInstitutionWTService userAndInstituionWTService;

    @Resource(name = "institutionWTService")
    private InstitutionWTAPIService institutionService;

    /**
     * 新增孩子申请
     *
     * @param request
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Object create(
            @RequestBody @Valid ChildApplyRequest request) {

        List<ChildApplyResponse> list = childApplyService.list(request);
        if (!(list.isEmpty()))
            throw new BusinessException("childApply.exist");
        if (request.getUserId() == null)
            request.setUserId(getCurrentUserId());
        InstitutionResponse institutionResponse =
                institutionService.getById(request.getCmInstitutionId());
        if (institutionResponse == null) {
            throw new BusinessException("institutionResponse.not.exist");
        }
        childApplyService.addorUpdate(request);
        Sms sms = new Sms(request.getCmInstitutionId(), request, institutionResponse);
        sms.run();
        return new BaseMessage();
    }

    /**
     * 发送SMS
     */
    public void sendSms(Long cmInstitutionId, ChildApplyRequest name,
                        InstitutionResponse institutionResponse) {

        UserAndInstituionRequest request = new UserAndInstituionRequest();
        request.setCmInstitutionId(cmInstitutionId);
        request.setRoleType(RoleTypeEnum.ADMIN.getValue());
        request.setState(AuditStateEnum.TG_TG.getLongValue());
        List<UserAndInstituionResponse> list = userAndInstitutionService.list(request);
        for (int i = 0; i < list.size(); i++) {
            UserAndInstituionResponse u = list.get(i);
            User user = userService.getByUserId(u.getUserId());
            initChat(user, name, institutionResponse);
        }
    }

    public void initChat(User user, ChildApplyRequest request,
                         InstitutionResponse institutionResponse) {

        String key = user.getPhone() + user.getApp();
        // 环信默认密码wtp@123456,如果用户用验证码注册，就用默认密码
        ChatInstance.getChat(AppType.APESTAR.getValue())
                .transmissionMessageFromOneToOne(PeoPleType.PARENT.getValue(), key,
                        getCurrentUser().getName() + "提交小孩" + request.getName() + "申请加入"
                                + institutionResponse.getInstitutionName(), MessageType.TXT.getValue(),
                        MessageWTType.JZYQ.getValue());
    }

    /**
     * 删除孩子申请
     *
     * @param id
     */
    @RequestMapping(value = "/del/{id}", method = RequestMethod.GET)
    public Object del(
            @PathVariable("id") Long id) {

        childApplyService.del(id);
        return new BaseMessage();
    }

    /**
     * 查询孩子申请
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/lisForPage", method = RequestMethod.POST)
    public List<ChildApplyResponse> lisForPage(@RequestBody ListChildApplyRequest request) {

        List list = childApplyService.lisForPage(request);
        ChildApplyDataConvert.convertToCustomerResponseList(list);
        return list;
    }

    /**
     * 审核孩子申请
     *
     * @param request
     */
    @RequestMapping(value = "/auditChildApply", method = RequestMethod.POST)
    public Object auditChildApply(@RequestBody @Valid AuditChildApplyRequest request) {

        if (request.getApplyId() == null)
            throw new BusinessException("childApply.no.id");
        ChildApply childapply = childApplyService.find(request.getApplyId());
        if (childapply == null || !(AuditStateEnum.TG_DD.getValue()
                .equals(childapply.getState()))) {
            throw new BusinessException("childApply.have.audit");
        }

        if (request.getCmInstitutionId() == null) {
            request.setCmInstitutionId(this.getInstitutionId());
        }
        rosterService.applyChild(request);
        return new BaseMessage();
    }

    /**
     * 孩子是否申请
     *
     * @param request
     */
    @RequestMapping(value = "/childIsHave", method = RequestMethod.POST)
    public Object childIsHave(
            @RequestBody @Valid AuditChildApplyRequest request) {

        // request.setName(null);
        List list = rosterService.list(request);
        return list;
    }

    public class Sms extends Thread {

        Long cmInstitutionId;

        ChildApplyRequest name;

        InstitutionResponse institutionResponse;

        public Sms(Long cmInstitutionId, ChildApplyRequest name,
                   InstitutionResponse institutionResponse) {
            this.cmInstitutionId = cmInstitutionId;
            this.name = name;
            this.institutionResponse = institutionResponse;
        }

        @Override
        public void run() {

            sendSms(cmInstitutionId, name, institutionResponse);
        }
    }
}